package com.oocl.jmsbook.producer.jms;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.log4j.Logger;

import com.oocl.jmsbook.util.JMSUtil;

public class BookJMSSender {
	
	private static final Logger LOGGER = Logger.getLogger(BookJMSSender.class);
	
	public static void readFileAndsendMessage(String filename) {
		BufferedReader reader = null;
		Connection conn = JMSUtil.createConnection();
		Destination queue = JMSUtil.getQueue();
		Session sess = null;
		MessageProducer producer = null;

		try {
			conn.start();
			sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
			producer = sess.createProducer(queue);
			
			reader = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
			String line;
			while ((line = reader.readLine()) != null) {
				TextMessage textMsg = sess.createTextMessage(line);
				LOGGER.info("Sending: " + line);
				producer.send(textMsg);
			}
		} catch (JMSException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			JMSUtil.close(producer, null, sess, conn);
		}
	}
}
